package com.cloudspace.jindun.activity.dianhua;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.error.VolleyError;
import com.cloudspace.jindun.R;
import com.cloudspace.jindun.activity.CustomTitleBaseActivity;
import com.cloudspace.jindun.adapter.ContactAddAdatper;
import com.cloudspace.jindun.adapter.ContactOrganizationAdapter;
import com.cloudspace.jindun.dao.ContactPerson;
import com.cloudspace.jindun.manager.ContactPersonManager;
import com.cloudspace.jindun.model.ContactPersonListResult;
import com.cloudspace.jindun.model.Organization;
import com.cloudspace.jindun.model.OrganizationListResult;
import com.cloudspace.jindun.model.Person;
import com.cloudspace.jindun.model.RemarkResult;
import com.cloudspace.jindun.network.api.API;
import com.cloudspace.jindun.network.base.ApiCallback;
import com.cloudspace.jindun.ui.WordsNavigation;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.CallingUtils;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;

import java.util.ArrayList;
import java.util.List;

import static java.net.HttpURLConnection.HTTP_OK;


/**
 * Created by zengxianhua on 16/12/24.
 */

public class ContactActivity extends CustomTitleBaseActivity implements View.OnClickListener {
    public static final String TAG = ContactActivity.class.getSimpleName();

    private ListView firstListView;
    private ListView secondListView;
    private ListView thirdListView;
    private View thirdView;
    private WordsNavigation mWordsNavigation;

    private View splitFirst;
    private View splitSecond;
    private View splitThird;

    private View firstLy;
    private View secondLy;
    private View thirdLy;

    private TextView firstText;
    private TextView secondText;
    private TextView thirdText;

    private ContactOrganizationAdapter firstAdatper;
    private ContactOrganizationAdapter secondAdapter;
    private ContactAddAdatper thirdAdapter;

    private String firstSelectedOrig;
    private String secondSelectedOrig;

    private ArrayList<Organization> testOrigs = new ArrayList<Organization>();
    private List<Organization> firstOrgs = new ArrayList<Organization>();
    private List<Organization> secondOrgs = new ArrayList<Organization>();
    private List<Person> thirdPersons = new ArrayList<Person>();

    private boolean showAddedCheckBox = true;

    private void getFirstListData(){
        API.getInstance().getOrgApi().getOrig(TAG, "0000", new ApiCallback<OrganizationListResult>() {
            @Override
            public void handleResult(OrganizationListResult result, VolleyError error) {
                if (result != null && result.status == HTTP_OK && !ObjUtil.isEmpty(result.data)){
                    firstOrgs = result.data;
                    firstAdatper.setDatas(firstOrgs);
                    showView(1);
                }
            }
        });
    }

    private void getSecondListData(String orgId){
        if (TextUtils.isEmpty(orgId)){
            return;
        }


        API.getInstance().getOrgApi().getOrig(TAG, orgId, new ApiCallback<OrganizationListResult>() {
            @Override
            public void handleResult(OrganizationListResult result, VolleyError error) {
                if (result != null && result.status == HTTP_OK && !ObjUtil.isEmpty(result.data)){
                    secondOrgs = result.data;
                    secondAdapter.setDatas(result.data);
                    showView(2);
                }
            }
        });
    }

    private void getThirdListData(String orgId){
        if (TextUtils.isEmpty(orgId)){
            return;
        }


        API.getInstance().getOrgApi().getOrigPersons(TAG, orgId, new ApiCallback<ContactPersonListResult>() {
            @Override
            public void handleResult(ContactPersonListResult result, VolleyError error) {
                if (result != null && result.status == HTTP_OK && !ObjUtil.isEmpty(result.data)){
                    thirdPersons = result.data;
                    thirdAdapter.setDatas(result.data);
                    showView(3);
                }
            }
        });
    }



    private void showView(int viewIndex){
        Drawable drawableDown = getResources().getDrawable(R.drawable.icon_04);
        drawableDown.setBounds(0, 0, drawableDown.getMinimumWidth(), drawableDown.getMinimumHeight());

        Drawable drawableUp= getResources().getDrawable(R.drawable.icon_03);
        /// 这一步必须要做,否则不会显示.
        drawableUp.setBounds(0, 0, drawableUp.getMinimumWidth(), drawableUp.getMinimumHeight());

        switch (viewIndex){
            case 1:
                splitFirst.setVisibility(View.VISIBLE);
                splitSecond.setVisibility(View.GONE);
                splitThird.setVisibility(View.GONE);
                firstListView.setVisibility(View.VISIBLE);
                secondListView.setVisibility(View.GONE);
                thirdView.setVisibility(View.GONE);
                firstText.setTextColor(getResources().getColor(R.color.zhutilan));
                secondText.setTextColor(getResources().getColor(R.color.light_black));
                thirdText.setTextColor(getResources().getColor(R.color.light_black));
                showSelectedOrig();
                firstText.setCompoundDrawables(null,null,drawableUp,null);
                secondText.setCompoundDrawables(null,null,drawableDown,null);
                thirdText.setCompoundDrawables(null,null,drawableDown,null);

                break;

            case 2:
                splitFirst.setVisibility(View.GONE);
                splitSecond.setVisibility(View.VISIBLE);
                splitThird.setVisibility(View.GONE);
                firstListView.setVisibility(View.GONE);
                secondListView.setVisibility(View.VISIBLE);
                thirdView.setVisibility(View.GONE);
                showSelectedOrig();
                firstText.setTextColor(getResources().getColor(R.color.light_black));
                secondText.setTextColor(getResources().getColor(R.color.zhutilan));
                thirdText.setTextColor(getResources().getColor(R.color.light_black));
                firstText.setCompoundDrawables(null,null,drawableDown,null);
                secondText.setCompoundDrawables(null,null,drawableUp,null);
                thirdText.setCompoundDrawables(null,null,drawableDown,null);
                break;

            case 3:
                splitFirst.setVisibility(View.GONE);
                splitSecond.setVisibility(View.GONE);
                splitThird.setVisibility(View.VISIBLE);
                firstListView.setVisibility(View.GONE);
                secondListView.setVisibility(View.GONE);
                thirdView.setVisibility(View.VISIBLE);
                showSelectedOrig();
                firstText.setTextColor(getResources().getColor(R.color.light_black));
                secondText.setTextColor(getResources().getColor(R.color.light_black));
                thirdText.setTextColor(getResources().getColor(R.color.zhutilan));
                firstText.setCompoundDrawables(null,null,drawableDown,null);
                secondText.setCompoundDrawables(null,null,drawableDown,null);
                thirdText.setCompoundDrawables(null,null,drawableUp,null);
                break;

            default:
                break;
        }
    }

    private void showSelectedOrig() {
        if (!ObjUtil.isEmpty(firstSelectedOrig)){
            firstText.setText(firstSelectedOrig);
        }
        if (!ObjUtil.isEmpty(secondSelectedOrig)){
            secondText.setText(secondSelectedOrig);
        }
    }

    public static final String CAN_EDIT = "CAN_EDIT";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent() != null){
            showAddedCheckBox = getIntent().getBooleanExtra(CAN_EDIT, false);
        }

        setContentView(R.layout.activity_contacts, true);
        getTitleBar().setSimpleMode(getString(R.string.contacts));
        getTitleBar().setRightText(getString(R.string.finish));
        getTitleBar().setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addContacts();
            }
        });
        getTitleBar().setRightColor(getResources().getColor(R.color.white));
        initviews();
        getFirstListData();
    }

    //添加联系人
    private void addContacts() {
        if (ObjUtil.isEmpty(thirdAdapter)
                || ObjUtil.isEmpty(thirdAdapter.getChecked())
                || ObjUtil.isEmpty(thirdPersons)){
            return;
        }

        List<Integer> checked = thirdAdapter.getChecked();
        final List<ContactPerson> checkPerson = new ArrayList<ContactPerson>();


        String friendListStr = "";
        for (int i = 0; i < thirdPersons.size(); ++i){
            if (checked.get(i) == 1 && !ObjUtil.isEmpty(thirdPersons.get(i))){
                friendListStr = friendListStr + thirdPersons.get(i).getUserId() + ",";
                checkPerson.add(Person.contructContactPerson(thirdPersons.get(i)));
            }
        }

        if (friendListStr.contains(",")){
            friendListStr = friendListStr.substring(0, friendListStr.length()-1);
        }

        if (TextUtils.isEmpty(friendListStr)){
            ToastMaker.showToastShort(R.string.choose_person_first);
            return;
        }

        API.getInstance().getOrgApi().addFriend(TAG, UserSessionManager.getInstance().getUserId(), friendListStr,
                new ApiCallback<RemarkResult>() {
                    @Override
                    public void handleResult(RemarkResult result, VolleyError error) {
                        if (error == null && result != null && result.getStatus() == HTTP_OK){
                            ContactPersonManager.getInstance().addContactPerson(checkPerson);
                        }

                        finish();
                    }
                });

    }

    private void initviews() {
        firstListView = (ListView) findViewById(R.id.firstOrig);
        secondListView = (ListView) findViewById(R.id.secondOrig);

        splitFirst = findViewById(R.id.firstsplit);
        splitSecond = findViewById(R.id.secondsplit);
        splitThird = findViewById(R.id.thirdsplit);

        firstLy = findViewById(R.id.firstly);
        secondLy = findViewById(R.id.secondly);
        thirdLy = findViewById(R.id.thirdly);

        firstLy.setOnClickListener(this);
        secondLy.setOnClickListener(this);
        thirdLy.setOnClickListener(this);

        thirdView = findViewById(R.id.thirdList);
        thirdListView = (ListView) findViewById(R.id.thirdOrig);
        mWordsNavigation= (WordsNavigation) findViewById(R.id.MyWordsNavigation);

        firstAdatper = new ContactOrganizationAdapter();
        secondAdapter = new ContactOrganizationAdapter();
        thirdAdapter = new ContactAddAdatper(this, showAddedCheckBox);

        firstListView.setAdapter(firstAdatper);
        secondListView.setAdapter(secondAdapter);
        thirdListView.setAdapter(thirdAdapter);

        firstText = (TextView) findViewById(R.id.firstText);
        secondText = (TextView) findViewById(R.id.secondText);
        thirdText = (TextView) findViewById(R.id.thirdText);

        firstListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!ObjUtil.isEmpty(firstOrgs)){
                    Organization org = firstOrgs.get(position);
                    firstSelectedOrig = org.organName;
                    if (!ObjUtil.isEmpty(firstSelectedOrig) && firstSelectedOrig.length() > 4){
                        firstSelectedOrig = firstSelectedOrig.substring(0, 4) + "...";
                    }
                    if (org != null){
                        getSecondListData(org.currentOrganId);
                    }
                }
            }
        });

        secondListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (!ObjUtil.isEmpty(secondOrgs)){
                    Organization org = secondOrgs.get(position);
                    secondSelectedOrig = org.organName;

                    if (!ObjUtil.isEmpty(secondSelectedOrig) && secondSelectedOrig.length() > 4){
                        secondSelectedOrig = secondSelectedOrig.substring(0, 4) + "...";
                    }

                    if (org != null){
                        getThirdListData(org.currentOrganId);
                    }
                }
            }
        });

        thirdListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (thirdPersons != null){
                    Person person = thirdPersons.get(position);
                    if (person != null){
                        CallingUtils.showCallMethodDialog(ContactActivity.this, person);
                    }
                }
            }
        });
        //设置右侧触摸监听
        mWordsNavigation.setOnTouchingLetterChangedListener(new WordsNavigation.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = thirdAdapter.getPositionForSection(s.charAt(0));
                if(position != -1){
                    thirdListView.setSelection(position);
                }
                Log.e("LOG",position+"");
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.firstly:
                showView(1);
                break;
            case R.id.secondly:
                showView(2);
                break;

            case R.id.thirdly:
                showView(3);
                break;

            default:
                break;
        }
    }
}
